// WordUtil.java
package org.dealpdf.utils;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.dealpdf.model.OutboundDetail;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class WordUtil {
    public static void replacePlaceholders(XWPFDocument doc, Map<String, String> data) {
        // 处理段落
        for (XWPFParagraph paragraph : doc.getParagraphs()) {
            String text = paragraph.getText();
            if (text != null && !text.isEmpty()) {
                System.out.println("Paragraph text: " + text); // 调试输出
                for (Map.Entry<String, String> entry : data.entrySet()) {
                    String key = "[" + entry.getKey() + "]";
                    if (text.contains(key)) {
                        for (XWPFRun run : paragraph.getRuns()) {
                            String runText = run.getText(0);
                            if (runText != null && runText.contains(key)) {
                                run.setText(runText.replace(key, entry.getValue()), 0);
                            }
                        }
                    }
                }
            }
        }
        // 处理表格
        for (XWPFTable table : doc.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph paragraph : cell.getParagraphs()) {
                        String text = paragraph.getText();
                        if (text != null && !text.isEmpty()) {
                            System.out.println("Cell text: " + text); // 调试输出
                            for (Map.Entry<String, String> entry : data.entrySet()) {
                                String key = "[" + entry.getKey() + "]";
                                if (text.contains(key)) {
                                    for (XWPFRun run : paragraph.getRuns()) {
                                        String runText = run.getText(0);
                                        if (runText != null && runText.contains(key)) {
                                            run.setText(runText.replace(key, entry.getValue()), 0);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public static void addTable(XWPFDocument doc, List<OutboundDetail> details) {
        XWPFTable table = doc.createTable();
        XWPFTableRow headerRow = table.getRow(0);

        // 确保 headerRow 有足够的单元格
        while (headerRow.getTableCells().size() < 7) {
            headerRow.createCell();
        }
        String[] headers = {"序号", "订单号", "订单明细号", "产品名称", "单位", "数量", "单价"};
        for (int i = 0; i < headers.length; i++) {
            headerRow.getCell(i).setText(headers[i]);
        }
        for (int i = 0; i < details.size(); i++) {
            XWPFTableRow row = table.createRow();
            OutboundDetail detail = details.get(i);
            row.getCell(0).setText(String.valueOf(i + 1));
            row.getCell(1).setText(detail.getOrderId());
            row.getCell(2).setText(detail.getDetailId());
            row.getCell(3).setText(detail.getProductName());
            row.getCell(4).setText(detail.getUnit());
            row.getCell(5).setText(String.valueOf(detail.getQuantity()));
            row.getCell(6).setText(String.format("%.2f", detail.getUnitPrice()));
        }
    }

    public static void addQRCode(XWPFDocument doc, String qrContent) throws IOException, WriterException, InvalidFormatException {
        int size = 100;
        BitMatrix bitMatrix = new MultiFormatWriter().encode(qrContent, BarcodeFormat.QR_CODE, size, size);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "png", baos);
        byte[] qrImageBytes = baos.toByteArray();

        // 将图片数据添加到文档，返回 String 类型的 pictureId
        String pictureId = doc.addPictureData(qrImageBytes, XWPFDocument.PICTURE_TYPE_PNG);
        // 创建图片
        XWPFParagraph qrParagraph = doc.createParagraph();
        qrParagraph.setAlignment(ParagraphAlignment.RIGHT); // 右对齐
        XWPFRun qrRun = qrParagraph.createRun();
        qrRun.addPicture(
                new ByteArrayInputStream(qrImageBytes),
                XWPFDocument.PICTURE_TYPE_PNG,
                "qrcode.png",
                Units.toEMU(size),
                Units.toEMU(size)
        );
        // 调整位置（Word 中位置控制较复杂，需手动调整文档布局）
        // 建议在模板中预留右上角空间
    }
}